<template>
  <div>
    <h1>修改密码</h1>
    <div class="passwordShow">
      <el-form  label-width="100px" :model="userPasswordForm" :rules="userPasswordFormRules" ref="userPasswordFormRef">
        <el-form-item label="原密码:">
          <el-input v-model="userPasswordForm.oldPassword" disabled></el-input>
        </el-form-item>
        <el-form-item label="新密码:" prop="password">
          <el-input type="password" v-model="userPasswordForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码:" prop="checkPassword">
          <el-input type="password" v-model="userPasswordForm.checkPassword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updatePassword">修改</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserUpdatePassword',
  data () {
    const checkSpace = (rule, value, callback) => {
      const regSpace = /\s/
      if (!regSpace.test(value)) {
        return callback()
      }
      callback(new Error('不能有空格'))
    }
    // 确认密码的验证
    const checkPassword = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请再次输入密码'))
      }
      if (value === this.userPasswordForm.password || value === this.userPasswordForm.password) {
        return callback()
      }
      callback(new Error('两次输入的密码不一致'))
    }
    return {
      userPasswordForm: {
        uid: window.sessionStorage.getItem('uid'),
        oldPassword: '***************',
        password: '',
        checkPassword: ''
      },
      userPasswordFormRules: {
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 20,
            message: '请输入6~20个字符',
            trigger: 'blur'
          },
          {
            validator: checkSpace,
            trigger: 'blur'
          }
        ],
        checkPassword: [
          {
            required: true,
            validator: checkPassword,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    updatePassword () {
      this.$refs.userPasswordFormRef.validate(async (valid) => {
        if (!valid) {
          return false
        }
        const { data: res } = await this.$axios.post('/user/update', this.userPasswordForm)
        if (res.status !== 2000) {
          return this.$message.error('修改失败')
        }
        this.$message.success('修改成功')
        await this.$router.push('/user/info')
      })
    }
  }
}
</script>

<style scoped>
.passwordShow{
  width: 1000px;
  margin-left: auto;
  margin-right: auto;
}
h1{
  text-align: center;
}
.el-button{
  width: 80px;
  margin-left: 350px;
}
</style>
